﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CPPEI.Coolzon.UI.DataPartLib
{
    /// <summary>
    /// Interaction logic for DataTextAnimationLabel.xaml
    /// </summary>
    [XPartIcon("pack://application:,,,/CPPEI.Coolzon.UI.DataPartLib;component/Images/PartIcons/文字动画标签1.png")]
    [System.ComponentModel.DisplayName("文本动画标签")]
    public partial class DataTextAnimationLabel : DataAnimationLabelBase
    {
        private Dictionary<int, Grid> _labelDictonary;
        private Storyboard _animationStoryboard;

        public DataTextAnimationLabel()
        {
            InitializeComponent();
            _labelDictonary = new Dictionary<int, Grid>();
        }

        protected override void OnInit(PartContext context)
        {
            base.OnInit(context);
            XText = "文本动画标签";
        }

        #region Constructor

        protected override void OnActive(PartContext context)
        {
            base.OnActive(context);
            if (!string.IsNullOrWhiteSpace(XText))
            {
                TextAnimation(XText);
            }
        }
        protected override void OnDeactive(PartContext context)
        {
            OnDestory();
        }
        protected override void OnDestory()
        {
            if (_animationStoryboard != null)
            {
                _animationStoryboard.Stop();
                _animationStoryboard.Remove();
                _animationStoryboard = null;
            }
            gdLayout.Children.Clear();
            base.OnDestory();
        }
        protected override void OnDataItemBinding(ServiceProxy.DataServiceRef.DataItem dataItem)
        {
            StopAnimation();
            XText = dataItem.Value;
        }

        protected override void OnApplyXProperty()
        {
            base.OnApplyXProperty();
            if (!string.IsNullOrWhiteSpace(XText))
            {
                TextAnimation(XText);
            }
        }

        private void TextAnimation(string xText)
        {
            ClearAnimation();
            StopAnimation();
            _animationStoryboard = new Storyboard();
            _animationStoryboard.FillBehavior = FillBehavior.HoldEnd;
            _animationStoryboard.Completed += _animationStoryboard_Completed;
            
            gdLayout.Children.Clear();
            _labelDictonary.Clear();

            string itemValueString = xText;

            double everyWidth = GetEveryCharWeight(itemValueString.Length);

            int startIndex = 0, endIndex = itemValueString.Length, offset = 1;
            StackPanel sp = new StackPanel();
            sp.Orientation = Orientation.Horizontal;
            if (XFlowDirection != null && XFlowDirection.Equals("RightToLeft", StringComparison.OrdinalIgnoreCase))
            {
                sp.FlowDirection = FlowDirection.RightToLeft;
                startIndex = itemValueString.Length - 1;
                endIndex = -1;
                offset = -1;
            }
            sp.Width = Width;
            for (int i = startIndex; i != endIndex; i = i + offset)
            {
                char digital = itemValueString[i];
                Grid shadowGrid = new Grid();
                ImageBrush imageBrush = new ImageBrush(XDigitalImage==null? null : XDigitalImage.ImageSource);
                imageBrush.Stretch = Stretch.Fill;
                shadowGrid.Background = imageBrush;
                for (int shadowIndex = 1; shadowIndex <= 3; shadowIndex++)
                {
                    Label lb = new Label();
                    lb.Height = Height;
                    lb.Width = everyWidth;
                    lb.Margin = XLabelMargin;
                    lb.ClipToBounds = true;
                    lb.Effect = GetDropShadowEffect();
                    InitControl(lb);
                    shadowGrid.Children.Add(lb);
                }

                _labelDictonary.Add(i, shadowGrid);

                sp.Children.Add(shadowGrid);
            }
            gdLayout.Children.Add(sp);

            DoubleAnimation doubleAnimation = new DoubleAnimation(0, itemValueString.Length * itemValueString.Length, new Duration(TimeSpan.FromSeconds(XDataAnimationDuration)));
            Storyboard.SetTarget(doubleAnimation, this);
            Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath(DataTextAnimationLabel.DataAnimationProgressProperty));
            _animationStoryboard.Children.Add(doubleAnimation);

            if (_animationStoryboard != null)
            {
                _animationStoryboard.Begin();
            }
        }


        /// <summary>
        /// 初始化控件属性
        /// </summary>
        private void InitControl(Label lb)
        {
            if (XFontSize != 0)
            {
                lb.FontSize = XFontSize;
            }
            lb.HorizontalContentAlignment = XTextAlign;
            lb.VerticalContentAlignment = XTextVAlign;
            if (XFont != null)
            {
                lb.FontFamily = XFont;
            }
            lb.FontWeight = XFontWeight;
            if (XForeground != null)
            {
                lb.Foreground = XForeground.Brush;
            }
            lb.Height = Height;
        }
        #endregion
        
        /// <summary>
        /// 动画完成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _animationStoryboard_Completed(object sender, EventArgs e)
        {
            ClearAnimation();
            for (int textIndex = 0; textIndex < XText.Length; textIndex++)
            {
                foreach (var item in _labelDictonary[textIndex].Children)
                {
                    (item as System.Windows.Controls.Label).Content = XText[textIndex];
                }
            }
        }

        /// <summary>
        /// 清理动画，清理故事版中每个动画的target，防止内存溢出
        /// </summary>
        private void ClearAnimation()
        {
            if (_animationStoryboard != null)
            {
                foreach (Timeline tl in _animationStoryboard.Children)
                {
                    tl.ClearValue(Storyboard.TargetProperty);
                }
            }
        }
        private void StopAnimation()
        {
            if (_animationStoryboard != null)
            {
                _animationStoryboard.Completed -= _animationStoryboard_Completed;
                _animationStoryboard.Stop();
                _animationStoryboard.Remove();
                _animationStoryboard = null;
            }
        }
    }
}
